package library.common.util;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import java.io.File;

/**
 * @author Created by qiang.hou on 2017/12/19.
 * @version 1.0
 */
public class FileUtils {
    /**
     * @param fileUri Uri
     * @return File
     */
    public static File getUirFile(Uri fileUri) {
        return new File(fileUri.getPath());
    }

    /**
     * 根据url获取文件名
     *
     * @param url file Url
     * @return file name
     */
    public static String getFileNameWithURL(String url) {
        String name = null;
        if (!TextUtils.isEmpty(url)) {
            String decodedUrl = Uri.decode(url);
            if (!TextUtils.isEmpty(decodedUrl)) {
                // 先获取extension
                String extension = null;
                int ext = decodedUrl.lastIndexOf(".");
                if (ext != -1 && decodedUrl.length() - ext < 5) {
                    extension = decodedUrl.substring(ext);
                }
                int query = decodedUrl.indexOf("?");
                if (query > 0) {
                    decodedUrl = decodedUrl.substring(0, query);
                }
                query = decodedUrl.indexOf("#");
                if (query > 0) {
                    decodedUrl = decodedUrl.substring(0, query);
                }
                if (!decodedUrl.endsWith("/")) {
                    int index = decodedUrl.lastIndexOf("/") + 1;
                    if (index > 0) {
                        name = decodedUrl.substring(index);
                    }
                }
                if (!TextUtils.isEmpty(extension) && !TextUtils.isEmpty(name) && !name.contains(".")) {
                    name += extension;
                }
            }
        }
        return name;
    }

    /**
     * 根据content disposition生成文件名
     *
     * @param url  url
     * @param name file name
     * @return new name
     */
    public static String generateFileKey(String url, String name) {
        return System.currentTimeMillis() + url + name;
    }

    /**
     * file to Uri
     *
     * @param context Context
     * @param file    File
     * @return Uri
     */
    public static Uri getProviderUri(Context context, File file) {
        return getProviderUri(context, context.getPackageName() + ".FileProvider", file);
    }

    /**
     * file to Uri
     *
     * @param context   Context
     * @param authority authority context.getPackageName()+".FileProvider"
     * @param file      File
     * @return Uri
     */
    public static Uri getProviderUri(Context context, String authority, File file) {
        /*
        使用FileProvider步骤
        1. 在AndroidManifest.xml文件中注册provider
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
        2. 在资源文件xml中，创建path路径
        <?xml version="1.0" encoding="utf-8"?>
        <resources>
            <paths>
                <files-path name="my_files" path="text/"/>
                <cache-path name="my_cache" path="text/" />
                <external-files-path name="external-files-path" path="text/" />
                <external-path name="my_external_path" path="text/" />
            </paths>
        </resources>
        <!--
            <files-path/>代表的根目录： Context.getFilesDir()
            <external-path/>代表的根目录: Environment.getExternalStorageDirectory()
            <cache-path/>代表的根目录: getCacheDir()
        -->
        3. 在代码中用FileProvider.getUriForFile获取引用
        （1）文件的绝对路径与第二步指定的文件目录保持一致：
                (假设包名为com.ysx.fileproviderserver)。如上边的代码的文件的绝对路径为/data/data/com.ysx.fileproviderserver/files/text/hello.txt，
                对应paths中的内容为:<files-path name="my_files" path="text/"/>。
        （2）getUriForFile()的第二个参数是authority，与manifest文件中声明的authorities保持一致。
        4. 调用场景：
        （1）调用相机：
        public static void takePicture(Context context, String authority, File file, int requestCode) {
            Intent intent = new Intent();
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(context, authority, file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                imageUri = Uri.fromFile(file);
            }
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            activity.startActivityForResult(intent, requestCode);
        }
        （2）调用安装器
        public static void installApk(Context context, String authority, File file) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                data = FileProvider.getUriForFile(context, authority, file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = Uri.fromFile(file);
            }
            intent.setDataAndType(data, INSTALL_TYPE);
            context.startActivity(intent);
        }
         */
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), authority, file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

}
